﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cricket.LinqModel;
using Cricket.LinqData;
using System.Web.Services;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class AddBetting : System.Web.UI.Page
{
    #region Variable Declaration
    IDataRepository _dataObject = new DataRepository();
    MatchSchedule matchSchedule;
    List<MatchSchedule> matchSchedules;
    BettingType bettingType;
    List<BettingType> bettingTypes;
    MatchType matchType;
    List<MatchType> matchTypes;
    Betting betting;
    static IDataRepository _dataObject1 = new DataRepository();
    static Betting bet;
    static MatchSchedule ms1;
    static CricketGeneral crickGen;
    public string id = "";
    FancyNineEleven fancy;
    static FancyNineEleven fancyBet;


    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            HttpCookie cookie = Request.Cookies["Admin"];
            if (cookie == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                if (cookie["BetId"] == "1")
                {
                    drpBettingType.SelectedValue = "2";
                    drpBettingType.Enabled = false;
                }
                else if (cookie["BetId"] == "2")
                {
                    drpBettingType.SelectedValue = "1";
                    drpBettingType.Enabled = false;
                }
                hdnAdminId.Value = cookie["AdminId"];
                bindBettingType();
                bindMatchType();
                if (Request.QueryString["Id"] != null)
                    getDropdownsSelected(Convert.ToInt32(Request.QueryString["Id"].ToString()));
            }
        }
    }

    private void bindMatch(int matchType)
    {
        matchSchedule = new MatchSchedule(_dataObject);
        List<GetTodayMatcheResult> lstResult = new List<GetTodayMatcheResult>();
        lstResult = matchSchedule.GetTodayMatches(matchType);
        if (lstResult.Count > 0)
        {
            drpMatch.DataSource = lstResult;
            drpMatch.DataTextField = "Teams";
            drpMatch.DataValueField = "Id";
            drpMatch.DataBind();
            drpMatch.Items.Insert(0, new ListItem("Select Match", "0"));
        }
        else
        {
            drpMatch.DataSource = null;
            drpMatch.DataBind();
            drpMatch.Items.Insert(0, new ListItem("Select Match", "0"));
        }
    }

    private void bindMatchType()
    {
        matchType = new MatchType(_dataObject);
        matchTypes = new List<MatchType>();
        matchTypes = matchType.GetAllMatchType();
        if (matchTypes.Count > 0)
        {
            drpMatchType.DataSource = matchTypes;
            drpMatchType.DataTextField = "Type";
            drpMatchType.DataValueField = "Id";
            drpMatchType.DataBind();
            drpMatchType.Items.Insert(0, new ListItem("Select Match Type", "0"));
        }
    }

    private void bindBettingType()
    {
        bettingType = new BettingType(_dataObject);
        bettingTypes = new List<BettingType>();
        bettingTypes = bettingType.GetAllBettingType();
        if (bettingTypes.Count > 0)
        {
            drpBettingType.DataSource = bettingTypes;
            drpBettingType.DataTextField = "Type";
            drpBettingType.DataValueField = "Id";
            drpBettingType.DataBind();
            drpBettingType.Items.Insert(0, new ListItem("Select Betting Type", "0"));
        }
    }
    protected void drpMatchType_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindMatch(Convert.ToInt32(drpMatchType.SelectedValue));
    }
    protected void drpMatch_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (drpMatch.SelectedItem.Text.ToLower() != "select match" && drpMatch.SelectedItem.Text.ToLower() != "select match type")
        {
            matchSchedule = new MatchSchedule(_dataObject);
            List<GetMatchDetailsResult> lstResult = new List<GetMatchDetailsResult>();
            lstResult = matchSchedule.GetMatchDetails(Convert.ToInt32(drpMatch.SelectedValue));
            lblTeamA.Text = lstResult[0].Abb1;
            lblTeamB.Text = lstResult[0].Abb2;
            hdnTeamAId.Value = Convert.ToString(lstResult[0].TeamAId);
            hdnTeamBId.Value = Convert.ToString(lstResult[0].TeamBId);
        }
    }
    [WebMethod]
    public static int SaveBettingRecords(int bettingTypeId, int matchTypeId, int matchScheduleId, int teamId, string over, string lagadiRate, string khadhiRate, string drawLagadi, string drawKhadhi, bool isDraw, string tieLagadi, string tieKhadhi, bool isTie)
    {
        var response = HttpContext.Current.Request;

        HttpCookie cookie = response.Cookies["Admin"];
        var adminId = "";
        if (cookie["AdminId"] != null)
            adminId = cookie["AdminId"];

        bet = new Betting(_dataObject1);
        crickGen = new CricketGeneral();
        bet.BettingTypeId = bettingTypeId;
        bet.AdminId = Convert.ToInt32(adminId);
        bet.MatchTypeId = matchTypeId;
        bet.MatchScheduleId = matchScheduleId;
        bet.Over = over;

        bet.TeamId = teamId;
        if (bettingTypeId == 1)
        {
            bet.LagadiRate = khadhiRate;
            bet.KhadhiRate = lagadiRate;
        }
        else
        {
            bet.LagadiRate = lagadiRate;
            bet.KhadhiRate = khadhiRate;
        }
        bet.DrawLagadi = drawLagadi;
        bet.DrawKhadhi = drawKhadhi;
        bet.IsTie = isTie;
        bet.IsDraw = isDraw;
        bet.TieLagadi = tieLagadi;
        bet.TieKhadhi = tieKhadhi;
        bet.IsDeleted = false;
        bet.CreatedBy = Convert.ToInt32(adminId);
        bet.CreatedDate = System.DateTime.Now;
        bet.IPAdded = crickGen.IPAddress(System.Web.HttpContext.Current);
        bet.CreateBetting();

        return 1;
    }
    [WebMethod]
    public static int UpdateBettingRecords(int bettingTypeId)
    {

        var response = HttpContext.Current.Request;
        HttpCookie cookie = response.Cookies["Admin"];
        var adminId = "";
        if (cookie["AdminId"] != null)
            adminId = cookie["AdminId"];

        bet = new Betting(_dataObject1);
        bet.IsDeleted = true;
        bet.BettingTypeId = bettingTypeId;
        bet.AdminId = Convert.ToInt32(adminId);
        bet.UpdateBetting();

        fancyBet = new FancyNineEleven(_dataObject1);
        fancyBet.IsDeleted = true;
        fancyBet.BettingTypeId = 5;
        fancyBet.AdminId = Convert.ToInt32(adminId);
        fancyBet.UpdateFancyNineEleven();
        return 1;
    }


    [WebMethod]
    public static int UpdateBettingRecordsForMatch(int bettingTypeId, string lagadi, string khadhi)
    {

        var response = HttpContext.Current.Request;
        HttpCookie cookie = response.Cookies["Admin"];
        var adminId = "";
        if (cookie["AdminId"] != null)
            adminId = cookie["AdminId"];

        bet = new Betting(_dataObject1);
        bet.IsDeleted = true;
        bet.BettingTypeId = bettingTypeId;
        bet.AdminId = Convert.ToInt32(adminId);
        bet.LagadiRate = lagadi;
        bet.KhadhiRate = khadhi;
        bet.UpdateBettingForMatch();
        return 1;
    }
    [WebMethod]
    public static int UpdateBettingForDrawRecords(int bettingTypeId)
    {
        var response = HttpContext.Current.Request;
        HttpCookie cookie = response.Cookies["Admin"];
        var adminId = "";
        if (cookie["AdminId"] != null)
            adminId = cookie["AdminId"];

        bet = new Betting(_dataObject1);
        bet.IsDeleted = true;
        bet.BettingTypeId = bettingTypeId;
        bet.AdminId = Convert.ToInt32(adminId);
        bet.UpdateBettingForDraw();
        return 1;
    }

    [WebMethod]
    public static int UpdateBettingForTieRecords(int bettingTypeId)
    {
        var response = HttpContext.Current.Request;
        HttpCookie cookie = response.Cookies["Admin"];
        var adminId = "";
        if (cookie["AdminId"] != null)
            adminId = cookie["AdminId"];

        bet = new Betting(_dataObject1);
        bet.IsDeleted = true;
        bet.BettingTypeId = bettingTypeId;
        bet.AdminId = Convert.ToInt32(adminId);
        bet.UpdateBettingForTie();
        return 1;
    }
    private static DataTable GetData(string query)
    {
        string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = query;
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        return dt;
                    }
                }
            }
        }
    }
    private void getDropdownsSelected(int matchScheduleId)
    {
        DataTable dt = GetData("select * from MatchSchedule where Id = " + matchScheduleId.ToString());
        drpMatchType.SelectedValue = dt.Rows[0]["MatchType"].ToString();
        bindMatch(Convert.ToInt32(drpMatchType.SelectedValue));
        drpMatch.SelectedValue = matchScheduleId.ToString();
        drpMatch_SelectedIndexChanged(null, null);
    }
    protected void btnStopAll_Click(object sender, EventArgs e)
    {
        betting = new Betting(_dataObject);
        var response = HttpContext.Current.Request;
        HttpCookie cookie = response.Cookies["Admin"];
        var adminId = "";
        if (cookie["AdminId"] != null)
            adminId = cookie["AdminId"];
        int Count = betting.StopAllBetting(Convert.ToInt32(adminId));
        txtTeamAOver.Text = string.Empty;
        txtTeamALagadi.Text = string.Empty;
        txtTeamAKhadhi.Text = string.Empty;
        txtTeamBOver.Text = string.Empty;
        txtTeamBLagadi.Text = string.Empty;
        txtTeamBKhadhi.Text = string.Empty;
        txtDrawLagadi.Text = string.Empty;
        txtDrawKhadhi.Text = string.Empty;
        txtTieLagadi.Text = string.Empty;
        txtTieKhadhi.Text = string.Empty;

    }

    protected void btnReport_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["Admin"];
        grdCustomerBettingMatch.Visible = true;
        matchSchedule = new MatchSchedule(_dataObject);
        List<GetMatchDetailsResult> lstResult = new List<GetMatchDetailsResult>();
        lstResult = matchSchedule.GetMatchDetails(Convert.ToInt32(drpMatch.SelectedValue));
        grdCustomerBettingMatch.Columns[1].HeaderText = lstResult[0].Abb1;
        grdCustomerBettingMatch.Columns[2].HeaderText = lstResult[0].Abb2;

        DataTable dt = new DataTable();
        //dt = GetData(string.Format("SELECT T.Abbrivation,CASE CB.BetFor WHEN 'L' THEN B.LagadiRate ELSE B.KhadhiRate END AS Rate,CB.BetFor AS BettingFor,CB.Rate AS BettingAmount, TeamAAmount AS TeamAAmount, TeamBAmount AS TeamBAmount, TieAmount AS TieAmount, DrawAmount AS DrawAmount from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId INNER JOIN Team T ON T.Id = B.TeamId WHERE C.Id = '{0}' AND CB.MatchSchduleId = '{1}'  AND B.BettingTypeId = 2 ORDER BY CB.Createddate DESC", Convert.ToInt32(cookie["ClientId"]), drpMatch.SelectedValue));
        dt = GetData(string.Format("SELECT (SUM(CAST(CB.Rate AS Decimal(18,2))) * (1)) AS BettingAmount, (SUM(TeamAAmount) * (-1)) AS TeamAAmount,(SUM(TeamBAmount) *(-1)) AS TeamBAmount, (SUM(TieAmount) * (-1)) AS TieAmount, (SUM(DrawAmount) * (-1)) AS DrawAmount from Client C INNER JOIN Admin A ON C.AdminId = A.Id INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON CB.BettingId = B.Id WHERE B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 2"));
        grdCustomerBettingMatch.DataSource = dt;
        grdCustomerBettingMatch.DataBind();

        grdCustomerBettingSession.Visible = true;
        //grdCustomerBettingSession.DataSource = GetData(string.Format("SELECT T.Abbrivation,b.[Over],CASE CB.BetFor WHEN 'L' THEN B.KhadhiRate ELSE B.LagadiRate END AS Rate,CASE CB.BetFor WHEN 'L' THEN 'K' ELSE 'L' END AS BettingFor,CB.Rate AS BettingAmount from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId INNER JOIN Team T ON T.Id = B.TeamId WHERE C.Id = '{0}' AND CB.MatchSchduleId = '{1}'  AND B.BettingTypeId = 1 ORDER BY CB.Createddate DESC", Convert.ToInt32(cookie["ClientId"]), drpMatch.SelectedValue));
        DataTable dt1 = new DataTable();
        dt1 = GetData(string.Format("SELECT T.Abbrivation,b.[Over],CASE CB.BetFor WHEN 'L' THEN B.LagadiRate ELSE B.KhadhiRate END AS Rate, C.Username as FullName,CASE CB.BetFor WHEN 'L' THEN 'L' ELSE 'K' END AS BettingFor,CB.Rate AS BettingAmount,CONVERT(varchar(20),DATEADD(MI,30,DATEADD(hh,5,CB.CreatedDate)),113) As Date from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy Inner JOIN Admin A ON c.AdminId = A.Id INNER JOIN Betting B ON B.Id = CB.BettingId INNER JOIN Team T ON T.Id = B.TeamId  WHERE (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = '{0}' AND B.BettingTypeId = 1 AND CB.Is90110 IS NULL ORDER BY CB.Createddate DESC ", drpMatch.SelectedValue));
        grdCustomerBettingSession.DataSource = dt1;
        grdCustomerBettingSession.DataBind();


        grd90110.Visible = true;        
        DataTable dt2 = new DataTable();
        dt2 = GetData(string.Format("SELECT T.Abbrivation,b.[Over],CASE CB.BetFor WHEN 'L' THEN B.BettingRate ELSE B.BettingRate END AS Rate, C.Username as FullName,CASE CB.BetFor WHEN 'L' THEN 'L' ELSE 'K' END AS BettingFor,CB.Rate AS BettingAmount,CONVERT(varchar(20),DATEADD(MI,30,DATEADD(hh,5,CB.CreatedDate)),113) As Date from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy Inner JOIN Admin A ON c.AdminId = A.Id INNER JOIN FancyNineEleven B ON B.Id = CB.BettingId INNER JOIN Team T ON T.Id = B.TeamId  WHERE (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = '{0}'  AND B.BettingTypeId = 5 AND CB.Is90110 = 1 ORDER BY CB.Createddate DESC ", drpMatch.SelectedValue));
        grd90110.DataSource = dt2;
        grd90110.DataBind();


        grdCustomerMatchReport.Columns[5].HeaderText = lstResult[0].Abb1;
        grdCustomerMatchReport.Columns[6].HeaderText = lstResult[0].Abb2;

        grdCustomerMatchReport.Visible = true;
        grdCustomerMatchReport.DataSource = GetData(string.Format("SELECT CASE WHEN B.IsDraw = 1 THEN CASE CB.BetFor WHEN 'L' THEN B.DrawLagadi ELSE B.DrawKhadhi END WHEN B.IsTie = 1 THEN CASE CB.BetFor WHEN 'L' THEN B.TieLagadi ELSE B.TieKhadhi END ELSE	CASE CB.BetFor WHEN 'L' THEN B.LagadiRate ELSE B.KhadhiRate END END AS Rate,CB.BetFor AS BettingFor,BettingAmount AS BettingAmount, TeamAAmount AS TeamAAmount,TeamBAmount AS TeamBAmount, TieAmount AS TieAmount, DrawAmount AS DrawAmount,T.Abbrivation As TeamName,CONVERT(varchar(20),DATEADD(MI,30,DATEADD(hh,5,CB.CreatedDate)),113) As Date, C.Username AS ClientName,CB.Rate AS Amount from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId INNER JOIN Team T ON B.TeamId = T.Id WHERE B.AdminId = '{0}' AND CB.MatchSchduleId = '{1}'  AND B.BettingTypeId = 2 ORDER BY CB.Createddate DESC", Convert.ToInt32(cookie["AdminId"]), drpMatch.SelectedValue));
        grdCustomerMatchReport.DataBind();


    }

    [WebMethod]
    public static List<GetCommonRateResult> getCurrentRate(int adminId)
    {
        IDataRepository _dataObject1 = new DataRepository();
        Admin admin;

        admin = new Admin(_dataObject1);
        List<GetCommonRateResult> lstResult = new List<GetCommonRateResult>();
        lstResult = admin.GetCommonRate(adminId);

        if (lstResult != null && lstResult.Count > 0)
            return lstResult;
        else
            return null;
    }

    [WebMethod]
    public static int StopAll(int adminId)
    {
        //var response = HttpContext.Current.Request;
        //HttpCookie cookie = response.Cookies["Admin"];
        //var adminId = "";
        //if (cookie["AdminId"] != null)
        //    adminId = cookie["AdminId"];
        Betting betting1 = new Betting(_dataObject1);
        int Count = betting1.StopAllBetting(Convert.ToInt32(adminId));
        return 1;

    }

    protected void grdCustomerBettingMatch_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (drpMatchType.SelectedItem.Text.ToLower() == "one day" || drpMatchType.SelectedItem.Text.ToLower() == "t20")
        {
            grdCustomerBettingMatch.Columns[3].Visible = false;
        }
        else
        {
            grdCustomerBettingMatch.Columns[3].Visible = true;
        }
    }

    protected void grdCustomerMatchReport_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        matchSchedule = new MatchSchedule(_dataObject);
        List<GetMatchDetailsResult> lst = new List<GetMatchDetailsResult>();
        lst = matchSchedule.GetMatchDetails(Convert.ToInt32(drpMatch.SelectedValue));
        if (lst.Count > 0)
        {
            if (lst[0].MatchType.ToLower() == "test")
            {
                grdCustomerMatchReport.Columns[7].Visible = true;
            }
            else
            {
                grdCustomerMatchReport.Columns[7].Visible = false;
            }

        }
    }


    [WebMethod]
    public static int SaveFancyBettingRecords(int matchTypeId, int matchScheduleId, int teamId, string over, string lagadiRate)
    {
        var response = HttpContext.Current.Request;

        HttpCookie cookie = response.Cookies["Admin"];
        var adminId = "";
        if (cookie["AdminId"] != null)
            adminId = cookie["AdminId"];

        fancyBet = new FancyNineEleven(_dataObject1);
        crickGen = new CricketGeneral();
        fancyBet.BettingTypeId = 5;
        fancyBet.AdminId = Convert.ToInt32(adminId);
        fancyBet.MatchTypeId = matchTypeId;
        fancyBet.MatchScheduleId = matchScheduleId;
        fancyBet.Over = over;
        fancyBet.TeamId = teamId;
        fancyBet.BettingRate = lagadiRate;

        fancyBet.IsDeleted = false;

        fancyBet.CreatedDate = System.DateTime.Now;
        fancyBet.IPAdded = crickGen.IPAddress(System.Web.HttpContext.Current);
        fancyBet.CreateFancyNineEleven();

        return 1;
    }
}